package com.example.stub.simulator;

import com.example.manager.ManagerClient;
import com.example.stub.SimulatorException;
import com.example.stub.SimulatorThread;
import com.example.terminal.TerminalClient;
import com.example.util.DataBuilder;
import com.example.util.DeviceFactory;

public class PackageThread extends SimulatorThread {

//	protected List<ClientContext> contexts = new ArrayList<>();
	
	protected String phone;
	
	protected int userId;
	
	protected int terminalId;
	
	protected String macid;
	
	protected int totalPackage;
	
	public PackageThread(int no, int totalThread) throws Exception {
		super(no, totalThread);
	}

	public PackageThread(int no, int totalThread, int totalPackage) throws Exception {
		this(no, totalThread);
		this.totalPackage = totalPackage;
	}
	
	@Override
	protected void preRun() throws Exception {
		macid = DataBuilder.buildRandomMacAddress();
		ManagerClient mClient = new ManagerClient(macid);
		
		phone = DeviceFactory.createPhoneNumber();
		mClient.register(phone, phone, phone + "@test.com");
		userId = mClient.getUserId();
		
		TerminalClient tClient = new TerminalClient();
		tClient.register();
		terminalId = tClient.getTerminalId();
	}

	@Override
	protected void execute() throws SimulatorException {
		try{
			ManagerClient mClient = new ManagerClient();
			mClient.start();
			mClient.login(phone, phone);
			
			TerminalClient tClient = new TerminalClient();
			tClient.register();
			tClient.start();
			
			// M通知状态服务器要连接T（状态服务器会通知T）
			mClient.requestAVConnect(terminalId);
			
			// M和T各自连接中转管理服务器，请求分配的转发服务器的IP和端口,中转管理服务器返回分配的IP和端口
			mClient.requestAVIPAndPort(terminalId);
			tClient.requestAVIPAndPort(userId);
			
			mClient.acceptVedio(userId, super.no);
			tClient.sendVedio(terminalId, totalPackage, super.no);
			
//			System.out.println("Thread[" + super.no + "] send " + totalPackage + " packages, received ");
		}catch(Exception e){
			throw new SimulatorException(super.no, e);
		}
	}
}

class ClientContext {
	ManagerClient mClient;
	TerminalClient tClient;
}